//
//  HoroscopeDetailInfoController.m
//  HoroscopeApp
//
//  Created by qinjiandong on 2018/7/13.
//  Copyright © 2018年 qinjiandong. All rights reserved.
//

#import "HoroscopeDetailInfoController.h"
#import "HoroRequest.h"
#import "HoroModel.h"
#import "Util.h"
#import "UIView+frame.h"
#import "SVProgressHUD.h"

/*
 日期btn 100000-100004
 进度条  110000-110007
 进度 111000-111007
 */

#define HoroChinese  @{@"Aquarius":@"水瓶座", \
@"Pisces":@"双鱼座", \
@"Aries":@"白羊座", \
@"Taurus":@"金牛座", \
@"Gemini":@"双子座", \
@"Cancer":@"巨蟹座", \
@"Leo":@"狮子座", \
@"Virgo":@"处女座", \
@"Libra":@"天秤座", \
@"Scorpio":@"天蝎座", \
@"Sagittarius":@"射手座", \
@"Capricornus":@"摩羯座" \
}

#define HoroDate  @{@"Aquarius":@"1.20-2.18", \
@"Pisces":@"2.19-3.20", \
@"Aries":@"3.21-4.19", \
@"Taurus":@"4.20-5.20", \
@"Gemini":@"5.21-6.21", \
@"Cancer":@"6.22-7.22", \
@"Leo":@"7.23-8.22", \
@"Virgo":@"8.23-9.22", \
@"Libra":@"9.23-10.23", \
@"Scorpio":@"10.24-11.22", \
@"Sagittarius":@"11.23-12.21", \
@"Capricornus":@"12.22-1.19" \
}

@interface HoroscopeDetailInfoController ()
@property (weak, nonatomic) IBOutlet UIImageView *signImageView;
@property (weak, nonatomic) IBOutlet UILabel *signNameLab;
@property (weak, nonatomic) IBOutlet UILabel *signTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *todayDateLab;
@property (weak, nonatomic) IBOutlet UILabel *contentLabel;
@property (weak, nonatomic) IBOutlet UILabel *luckyNumberLabel;

@property (weak, nonatomic) IBOutlet UIButton *dateButton1;
@property (weak, nonatomic) IBOutlet UIButton *dateButton2;
@property (weak, nonatomic) IBOutlet UIButton *dateButton3;
@property (weak, nonatomic) IBOutlet UIButton *dateButton4;
@property (weak, nonatomic) IBOutlet UIButton *dateButton5;

@property (weak, nonatomic) IBOutlet UIView *progressView1;
@property (weak, nonatomic) IBOutlet UIView *progressView2;
@property (weak, nonatomic) IBOutlet UIView *progressView3;


@property (nonatomic,assign)NSInteger selectedDateIndex;
@property (nonatomic,assign)CGFloat baseWidth;

@property (nonatomic,copy) NSString* horoname;
@property (nonatomic,strong)HoroModel *dataModel;
@property (nonatomic,strong)NSString *contentStr;
@end

@implementation HoroscopeDetailInfoController
- (void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    UIView *view = [self.view viewWithTag:110000];
    self.baseWidth = CGRectGetWidth(view.frame);
    NSDictionary* info = [[NSUserDefaults standardUserDefaults] objectForKey:@"userDefaults"];
    NSString* name = [info objectForKey:@"siginInfo"];
    self.signNameLab.text = name;
    self.signTimeLabel.text = [HoroDate objectForKey:name];
    self.horoname = name;
    [self setHoroImage:name];
    if (self.dataModel) {
        [self setPercent:self.dataModel];
        self.luckyNumberLabel.text = self.dataModel.number;
    }
    [self setDate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.selectedDateIndex = 1;
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1.0 green:124.0/255.0 blue:119.0/255.0 alpha:1];

    //255 124 119

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    self.navigationItem.title = @"iHoroscope";
  
    NSDictionary* info = [[NSUserDefaults standardUserDefaults] objectForKey:@"userDefaults"];
    NSString* name = [info objectForKey:@"siginInfo"];
    self.signNameLab.text = name;
    self.signTimeLabel.text = [HoroDate objectForKey:name];
    self.horoname = name;
    [self setHoroImage:name];
    [self requestData:name date:[Util getTodayDate]];
    
    //[[NSUserDefaults standardUserDefaults]setObject:infoDict forKey:@"userDefaults"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void) setDate {
    NSArray *dataArr = @[[Util getDateString:-1],[Util getDateString:0],[Util getDateString:1],[Util getDateString:2],[Util getDateString:3]];
    for (int i = 0; i < [dataArr count]; i++) {
        UIButton *dataBtn = [self.view viewWithTag:(100000+i)];
        [dataBtn setTitle:dataArr[i] forState:UIControlStateNormal];
}
    [self.todayDateLab setText:[Util getTodayString] ];
    
}

- (IBAction)selectDateAction:(UIButton *)sender {
    NSInteger index = sender.tag%10;
    BOOL isHavePay = [[[NSUserDefaults standardUserDefaults]objectForKey:@"PurchasedOK"]boolValue];
    if (index > 1 && !isHavePay) {
        UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil];
        self.navigationItem.backBarButtonItem = backBtn;
        [self performSegueWithIdentifier:@"HoroscopePayViewController" sender:self];
        return;
    }
    
    UIButton *preSelectBtn = [self.view viewWithTag:(100000+self.selectedDateIndex)];
    preSelectBtn.alpha = 0.5;
    sender.alpha = 1.0;
    self.selectedDateIndex = index;
    [self requesetDataWithIndex:index];
}

- (IBAction)leftBarButtonAction:(UIBarButtonItem *)sender {
    if ([[self.navigationController viewControllers] count]<=1) {
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UITableViewController *NCloginNC = [loginStoryboard instantiateViewControllerWithIdentifier:@"HoroscopeListViewController"];
        self.navigationController.viewControllers = @[NCloginNC,self];
    }
  
    [self.navigationController popViewControllerAnimated:YES];
}
- (IBAction)rightBarButtonAction:(UIBarButtonItem *)sender {
   
        UIStoryboard *loginStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        UITableViewController *NCloginNC = [loginStoryboard instantiateViewControllerWithIdentifier:@"HoroscopeInfoViewController"];
        self.navigationController.viewControllers = @[NCloginNC,self];
    
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - Table view data source
-(void) requesetDataWithIndex:(NSInteger) index {
    switch (index) {
        case 0:
//            NSString* yesterDay = [Util getOffsetDate:-1];
            [self requestData:self.horoname date:[Util getOffsetDate:-1]];
            break;
        
        case 1:
            
            [self requestData:self.horoname date:[Util getTodayDate]];
            break;
        
        case 2:
            [self requestData:self.horoname date:[Util getOffsetDate:1]];
            break;
        
        case 3:
            [self requestData:self.horoname date:[Util getOffsetDate:2]];
            break;
        
        case 4:
            [self requestData:self.horoname date:[Util getOffsetDate:3]];
            break;
            
        default:
            break;
    }
}

-(void) requestData:(NSString*) horoName date:(NSString*)date {

    weakify(self);
    [SVProgressHUD show];
    
    [HoroRequest getData:horoName withDate:date onCompletion:^(id result) {
        HoroModel* model = (HoroModel*)result;
        //NSLog(@"color:%@; money:%@; summary:%@;", model.color, model.money, model.summary);
        strongify(self);
        
        [self setSummury:model];
        [self setPercent:model];
        
        self.luckyNumberLabel.text = model.number;
        
        [SVProgressHUD dismiss];
    } onError:^(NSError* error) {
        [SVProgressHUD dismiss];
    }];
}

-(void) requestData:(NSString*) horoName type:(NSString*)type{
    NSString* chineseName = [HoroChinese objectForKey:horoName];
    
    weakify(self);
    [SVProgressHUD show];
    
    [HoroRequest getData:chineseName withType:type onCompletion:^(id result) {
        HoroModel* model = (HoroModel*)result;
        //NSLog(@"color:%@; money:%@; summary:%@;", model.color, model.money, model.summary);
        strongify(self);
        self.dataModel = model;
        [self setSummury:model];
        [self setPercent:model];
        
        self.luckyNumberLabel.text = model.number;
        [SVProgressHUD dismiss];
    } onError:^(NSError* error) {
        [SVProgressHUD dismiss];
    }];
}

// 自动布局后cell的高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 1) {
        CGSize size = [self.contentLabel sizeThatFits:CGSizeMake( CGRectGetWidth(self.contentLabel.frame), MAXFLOAT)];
      
        return [super tableView:tableView heightForRowAtIndexPath:indexPath]+size.height;//contenView高度和cell高度相差1
        }
    return [super tableView:tableView heightForRowAtIndexPath:indexPath];

    
}
-(void) setSummury:(HoroModel*) model {
    
    [HoroRequest getEnglishFromChinese: model.summary onCompletion:^(NSString* english) {
        [self.contentLabel setText:english];
        self.contentStr = english;
     
        [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];

    } onError:^(NSError* err) {
        
    } ];
    
}

-(void) setHoroImage:(NSString*)name {
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults]objectForKey:@"userDefaults"];
    NSInteger signStyle = [[dict objectForKey:@"selectedStyle"] integerValue];
    NSString *imageName = [NSString stringWithFormat:@"%@_%ld",name,signStyle];
    [self.signImageView setImage:[UIImage imageNamed:imageName]];
}

-(void) setPercent:(HoroModel*) model {
    NSArray *infoArr = @[model.health,model.all,model.love,[NSString stringWithFormat:@"%ld%%", ([self getNumberFromPercent: model.love] + [self getNumberFromPercent: model.health])/2],[NSString stringWithFormat:@"%ld%%", ([self getNumberFromPercent: model.love] + [self getNumberFromPercent: model.all])/2 ],[ NSString stringWithFormat:@"%ld%%",([self getNumberFromPercent: model.work] + [self getNumberFromPercent: model.money])/2 ], model.work,model.money];
    
    for (int i = 0; i < [infoArr count]; i++) {
        UILabel *numberLabel = [self.view viewWithTag:(111000+i)];
        
        numberLabel.text = infoArr[i]?:@"0";
         UIView* progressView = [self.view viewWithTag:(110000+i)];
        [self addProgressInnerView:progressView percent:infoArr[i]];
    }
    
//
//    UILabel* percent_healthy = [self.view viewWithTag:111000];
//    [percent_healthy setText:model.health];
//    UIView* progress_healthy = [self.view viewWithTag:10];
//    [self addProgressInnerView:progress_healthy percent:model.health];
//
//    UILabel* percent_intellect = [self.view viewWithTag:111001];
//    [percent_intellect setText:model.all];
//    UIView* progress_intellect = [self.view viewWithTag:11];
//    [self addProgressInnerView:progress_intellect percent:model.all];
//
//    UILabel* percent_love = [self.view viewWithTag:111002];
//    [percent_love setText:model.love];
//    UIView* progress_love = [self.view viewWithTag:12];
//    [self addProgressInnerView:progress_love percent:model.love];
//
//    UILabel* percent_emotion = [self.view viewWithTag:111003];
//    NSString* emotionPstr = [ NSString stringWithFormat:@"%d%%", ([self getNumberFromPercent: model.love] + [self getNumberFromPercent: model.health])/2 ];
//    [percent_emotion setText:emotionPstr];
//
//    UIView* progress_emotion = [self.view viewWithTag:13];
//    [self addProgressInnerView:progress_emotion percent: emotionPstr];
//
//    UILabel* percent_intuition = [self.view viewWithTag:111004];
//    NSString* intuitionPstr = [ NSString stringWithFormat:@"%d%%", ([self getNumberFromPercent: model.love] + [self getNumberFromPercent: model.all])/2 ];
//    [percent_intuition setText:intuitionPstr];
//
//    UIView* progress_intuition = [self.view viewWithTag:14];
//    [self addProgressInnerView:progress_intuition percent: intuitionPstr];
//
//    UILabel* percent_creatitive = [self.view viewWithTag:111005];
//    NSString* creatitivePstr = [ NSString stringWithFormat:@"%d%%",([self getNumberFromPercent: model.work] + [self getNumberFromPercent: model.money])/2 ];
//    [percent_creatitive setText: creatitivePstr];
//
//    UIView* progress_creatitive = [self.view viewWithTag:15];
//    [self addProgressInnerView:progress_creatitive percent: creatitivePstr];
//
//
//    UILabel* percent_work = [self.view viewWithTag:111006];
//    [percent_work setText:model.work];
//    UIView* progress_work = [self.view viewWithTag:16];
//    [self addProgressInnerView:progress_work percent:model.work];
//
//    UILabel* percent_money = [self.view viewWithTag:111007];
//    [percent_money setText:model.money];
//    UIView* progress_money = [self.view viewWithTag:17];
//    [self addProgressInnerView:progress_money percent:model.money];
////=======
//    UILabel* percent_healthy = [self.view viewWithTag:111000];
//    [percent_healthy setText:model.health];
//
//    UIView* progress_healthy = [self.view viewWithTag:10];
//    [self addProgressInnerView:progress_healthy percent:model.health];
//
//    UILabel* percent_intellect = [self.view viewWithTag:111001];
//    [percent_intellect setText:model.all];
//
//    UIView* progress_intellect = [self.view viewWithTag:11];
//    [self addProgressInnerView:progress_intellect percent:model.all];
//
//    UILabel* percent_love = [self.view viewWithTag:111002];
//    [percent_love setText:model.love];
//
//    UIView* progress_love = [self.view viewWithTag:12];
//    [self addProgressInnerView:progress_love percent:model.love];
//
//    UILabel* percent_emotion = [self.view viewWithTag:111003];
//    NSString* emotionPstr = [ NSString stringWithFormat:@"%d%%", ([self getNumberFromPercent: model.love] + [self getNumberFromPercent: model.health])/2 ];
//    [percent_emotion setText:emotionPstr];
//
//    UIView* progress_emotion = [self.view viewWithTag:13];
//    [self addProgressInnerView:progress_emotion percent: emotionPstr];
//
//    UILabel* percent_intuition = [self.view viewWithTag:111004];
//    NSString* intuitionPstr = [ NSString stringWithFormat:@"%d%%", ([self getNumberFromPercent: model.love] + [self getNumberFromPercent: model.all])/2 ];
//    [percent_intuition setText:intuitionPstr];
//
//    UIView* progress_intuition = [self.view viewWithTag:14];
//    [self addProgressInnerView:progress_intuition percent: intuitionPstr];
//
//    UILabel* percent_creatitive = [self.view viewWithTag:111005];
//    NSString* creatitivePstr = [ NSString stringWithFormat:@"%d%%",([self getNumberFromPercent: model.work] + [self getNumberFromPercent: model.money])/2 ];
//    [percent_creatitive setText: creatitivePstr];
//
//    UIView* progress_creatitive = [self.view viewWithTag:15];
//    [self addProgressInnerView:progress_creatitive percent: creatitivePstr];
//
//
//    UILabel* percent_work = [self.view viewWithTag:111006];
//    [percent_work setText:model.work];
//
//    UIView* progress_work = [self.view viewWithTag:16];
//    [self addProgressInnerView:progress_work percent:model.work];
//
//    UILabel* percent_money = [self.view viewWithTag:111007];
//    [percent_money setText:model.money];
//
//    UIView* progress_money = [self.view viewWithTag:17];
//    [self addProgressInnerView:progress_money percent:model.money];
//>>>>>>> Stashed changes
}

-(void) addProgressInnerView:(UIView*) parentView percent:(NSString*) percent {
    CGFloat rate = [self getNumberFromPercent: percent];
    CGFloat width = (parentView.frame.size.width * rate / 100)?:0;
    UIView* innerView = [[parentView subviews] objectAtIndex:0];
    innerView.layer.cornerRadius = 5.0f;
    [UIView animateWithDuration:1//动画持续时间
                          delay:0 //动画延迟执行的时间
                        options:UIViewAnimationOptionCurveEaseOut//动画的过渡效果
                     animations:^{
                         innerView.frame = CGRectMake(0, 0, width, innerView.frame.size.height);
                     }
                     completion:^(BOOL finished) {
                         //动画执行完毕后的操作
                     }];
}



-(NSInteger) getNumberFromPercent :(NSString*) percent {
    if(percent && percent.length > 0) {
        NSInteger ret = [[percent substringWithRange:NSMakeRange(0, percent.length - 1)] integerValue];
        return ret >= 0 ? ret : 0;
    }
    return 0;
}



@end
